package cn.well.cloud.exception.aop;


import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import cn.stylefeng.roses.kernel.model.response.ErrorResponseData;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import cn.stylefeng.roses.kernel.model.response.SuccessResponseData;
import cn.well.cloud.base.auth.exception.AuthException;
import cn.well.cloud.base.auth.exception.PermissionException;
import cn.well.cloud.exception.ParamIsNullException;
import cn.well.cloud.exception.TipsException;
import cn.well.cloud.exception.enums.BizExceptionEnum;
import io.jsonwebtoken.JwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import static cn.stylefeng.roses.core.util.HttpContext.getRequest;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 * Created by wison on 2019年8月21日.
 *
 */
@ControllerAdvice
@Order(1)
public class GlobalExceptionHandler {

    @SuppressWarnings("unused")
    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    
    
    /**
     * 拦截jwt相关异常
     */
    @ExceptionHandler(JwtException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResponseData jwtException(JwtException e) {
        return ResponseData.error(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
    }
    
    /**
     * 拦截请求方式错误异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResponseData serverError(Exception e) {
        return new ErrorResponseData(BizExceptionEnum.REQUEST_METHOD_ERROR.getCode(),BizExceptionEnum.REQUEST_METHOD_ERROR.getMessage());
    }
    
    /**
     * 拦截参数为空异常
     */
    @ExceptionHandler(ParamIsNullException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResponseData paramIsNullException(ParamIsNullException e) {
        return new ErrorResponseData(e.getCode(), e.getMessage());
    }
    
    /**
     * 拦截业务提示
     * @param e
     * @return
     * wison
     * 2019年8月27日
     */
    @ExceptionHandler(TipsException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseData tipsException(TipsException e) {
        return new SuccessResponseData(e.getCode(), e.getMessage(),null);
    }
    
    /**
     * 认证异常--认证失败（账号密码错误，账号被冻结，token过期等）
     */
    @ExceptionHandler(AuthException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ErrorResponseData unAuth(AuthException e) {
        return new ErrorResponseData(e.getCode(), e.getMessage());
    }

    /**
     * 认证异常--没有访问权限
     */
    @ExceptionHandler(PermissionException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ErrorResponseData permissionExpection(PermissionException e) {
        return new ErrorResponseData(e.getCode(), e.getMessage());
    }

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorResponseData bussiness(ServiceException e) {
        log.error("业务异常:", e);
        return ResponseData.error(e.getCode(), e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorResponseData notFount(RuntimeException e) {
//        if (LoginContextHolder.getContext().hasLogin()) {
//            LogManager.me().executeLog(LogTaskFactory.exceptionLog(LoginContextHolder.getContext().getUserId(), e));
//        }
        // TODO 存储异常
        getRequest().setAttribute("tip", "服务器未知运行时异常");
        log.error("运行时异常:", e);
        return new ErrorResponseData(BizExceptionEnum.SERVER_ERROR.getCode(), BizExceptionEnum.SERVER_ERROR.getMessage());
    }
    
    /**
     * 拦截post请求 Content type 'text/plain;charset=UTF-8' not supported 异常
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorResponseData notSupported(RuntimeException e) {  
        return new ErrorResponseData(BizExceptionEnum.SERVER_ERROR.getCode(), BizExceptionEnum.SERVER_ERROR.getMessage());
    }
    
}
